package fetcher

import (
	"ahutoj/web/service/originJudge/proxyPool/ip"
	"ahutoj/web/utils"
	"encoding/json"
	"net/url"
	"strconv"

	"github.com/sirupsen/logrus"
)
type IpDocResp struct {
	Data []struct {
		IP       string `json:"ip"`
		Addr     string `json:"addr"`
		ProxyType string `json:"proxy_type"`
	} `json:"data"`
}
func IpDoc() []*ip.IP {
	logrus.Info("[ipDoc] fetch start")
	defer func() {
		if r := recover(); r!= nil {
			logrus.Errorln("[ipDoc] fetch panic:", r)
		}
	}()
	list := make([]*ip.IP, 0)

	indexUrl := "https://www.docip.net/data/free.json"
	resp,err:=utils.DoRequest(utils.GET, indexUrl, nil,nil,nil)
	if err!= nil {
		return list
	}
	defer resp.Body.Close()
	body, err := utils.ParseRespToByte(resp)
	if err!= nil {
		return list
	}
	var ipDocResp IpDocResp
	err = json.Unmarshal(body, &ipDocResp)
	if err!= nil {
		logrus.Errorln("[ipDoc] parse json error:", err)
		return list
	}
	for _, item := range ipDocResp.Data {
		ip := new(ip.IP)
		ip.CreateTime=utils.FormatDateTime()
		ip.UpdateTime=utils.FormatDateTime()
		ip.ProxySource="https://www.docip.net/data/free.json"
		var uRL string
		switch item.ProxyType{
		case "1":
			uRL = "http://" + item.IP
			ip.ProxyType = "HTTP"
		case "2":
			uRL = "https://" + item.IP
			ip.ProxyType = "HTTPS"
		default:
			logrus.Warnf("[ipDoc] proxy type %v not support", item.ProxyType)
		}
		parsedIP,err := url.Parse(uRL)
		if err!= nil {
			logrus.Errorln("[ipDoc] parse ip error:", err)
			continue
		}
		ip.ProxyHost = parsedIP.Host
		port,_ := strconv.ParseInt(parsedIP.Port(), 10, 64)
		ip.ProxyPort = int(port)
		ip.ProxyLocation=item.Addr
		list = append(list, ip)
	}	
	// logrus.Infof("[ipDoc] fetch end, get %v proxies",list )
	return list
}
